﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities.Tracking;
using System.Activities.Statements.Tracking;
using Anagramme.Views;
using System.ComponentModel;
using System.Activities;
using System.ComponentModel.Composition;

namespace Anagramme.Views
{
    /// <summary>
    /// Manager de workflow
    /// </summary>
    [Export(typeof(IViewWorkflowManager))]
    public class ViewWorkflowManager : TrackingParticipant, Anagramme.Views.IViewWorkflowManager
    {
        #region Constructors
        /// <summary>
        /// Crée une nouvelle instance de la classe <see cref="ViewWorkflowManager"/>
        /// </summary>
        public ViewWorkflowManager()
        {
            this._workflowHost = new WorkflowApplication(new ViewWorkflow());
            this._workflowHost.Extensions.Add(this);
        }
        #endregion

        #region Fields
        private EventHandler<ViewWorkflowEventArgs> _messageReceived;
        private WorkflowApplication _workflowHost;
        #endregion

        #region IViewWorkflowManager Implementation
        /// <summary>
        /// Evènement soulevé lors de la réception d'un message
        /// </summary>
        public event EventHandler<ViewWorkflowEventArgs> MessageReceived
        {
            add { _messageReceived += value; }
            remove { _messageReceived -= value; }
        }

        /// <summary>
        /// Démarre le workflow
        /// </summary>
        public void Run()
        {
            this._workflowHost.Run();
        }

        /// <summary>
        /// Envoie d'un message au workflow
        /// </summary>
        /// <param name="content">Message à envoyer</param>
        public void SendMessage(string content)
        {
            this._workflowHost.ResumeBookmark(content, null);
        }
        #endregion

        #region Methods
        private void OnMessageReceived(string message)
        {
                if (_messageReceived != null) { _messageReceived(this, new ViewWorkflowEventArgs(message)); }
        }
        #endregion

        #region TrackingParticipant Overrides
        /// <summary>
        /// Permet de traiter l'enregistrement de suivi de façon synchrone.
        /// </summary>
        /// <param name="record">Enregistrement de suivi généré.</param>
        /// <param name="timeout">Période après laquelle le fournisseur abandonne la tentative.</param>
        protected override void Track(TrackingRecord record, TimeSpan timeout)
        {
            ViewTrackingRecord trackingRecord = record as ViewTrackingRecord;
            if (trackingRecord != null)
            {
                this.OnMessageReceived(trackingRecord.Name);
            }
        }
        #endregion
    }
}
